package com.btkjgc.service.impl;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import com.btkjgc.models.AdminUser;
import com.btkjgc.models.AjaxObj;
import com.btkjgc.models.Dictionary;
import com.btkjgc.models.ExceptionRecord;
import com.btkjgc.models.extend.ExceptionRecordModel;
import com.btkjgc.service.intf.TradeAbnormalGeneralService_Intf;
import com.btkjgc.utils.DateUtils;
import com.btkjgc.utils.ExcelExportor;
import com.btkjgc.utils.HibernateUtil;
import com.btkjgc.utils.LogUtils;

@Component
public class TradeAbnormalGeneralService_Impl extends BaseService_Impl implements TradeAbnormalGeneralService_Intf{
	
	static Logger logger = Logger.getLogger(TradeAbnormalGeneralService_Impl.class);
	
	@Override
	public void setpersonListData(HttpServletRequest request, ModelAndView mv, int pageIndex, int totalRecord,
			List<ExceptionRecordModel> personInfoList) {
		// TODO Auto-generated method stub
		
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements())
		{
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
		
		//审核状态
		String statussql = " SELECT dt.`key`,dt.`value` FROM dictionary_t dt WHERE dt.`name`='CheckStatus'";
				
		List<Dictionary> statusList = HibernateUtil.executeSQLQueryList(statussql,Dictionary.class);
		if(statusList.size() > 0)
		{
			mv.addObject("statusList", statusList);
		}
		
		mv.addObject("personInfoList", personInfoList);
 
		
		mv.addObject("currentpage", pageIndex);
		mv.addObject("totalRecord", totalRecord);
		
	}

	@Override
	public void setCompanyList(HttpServletRequest request, ModelAndView mv, int pageIndex, int totalRecord,
			List<ExceptionRecordModel> companyInfoList) {
		// TODO Auto-generated method stub
		
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements())
		{
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
	 
		//所属公司
		String companysql = " select aut.name value,CONCAT(id,'') 'key' from account_user_t aut where aut.type=1 and aut.del = 0";
		
		List<Dictionary> companyList = HibernateUtil.executeSQLQueryList(companysql,Dictionary.class);
		if (companyList.size() > 0)
		{
			mv.addObject("companyList", companyList);
		}
		
		//审核状态
		String statussql = " SELECT dt.`key`,dt.`value` FROM dictionary_t dt WHERE dt.`name`='CheckStatus'";
		
		List<Dictionary> statusList = HibernateUtil.executeSQLQueryList(statussql,Dictionary.class);
		if(statusList.size() > 0)
		{
			mv.addObject("statusList", statusList);
		}
		
		mv.addObject("companyInfoList", companyInfoList);
		mv.addObject("currentpage", pageIndex);
		mv.addObject("totalRecord", totalRecord);
		
	}

	@Override
	public void updateDelById(String id) {
		// TODO Auto-generated method stub
		AdminUser adminUser=getLoginUser();
		String hql = "update  exception_record_t set del=1,operdate=now(),operid="+adminUser.getId()+" where id =( ? )";
		HibernateUtil.executeSQLUpdate(hql, id);
	}

	@Override
	public ExceptionRecordModel getPersonByExchageid(String id) {
		// TODO Auto-generated method stub
		
		String sql="SELECT\n" +
				"	ait.available_balance balance,\n" +
				"	aut. NAME accountName,\n" +
				"	aut.account,\n" +
				"	aut.id accountid,\n" +
				"   eert.fare\n" +
				"FROM\n" +
				"	exchange_electric_record_t eert\n" +
				"LEFT JOIN car_account_log_t cat ON cat.id = eert.carAccountid\n" +
				"LEFT JOIN account_user_t aut ON aut.id = cat.accountid\n" +
				"LEFT JOIN account_info_t ait ON ait.accountid = aut.id\n" +
				"where eert.id='"+id+"'";
		
		ExceptionRecordModel exceptionRecordModel=(ExceptionRecordModel) HibernateUtil.executeSQLQueryObject(sql, ExceptionRecordModel.class);
		
		String varsql = " select SUM(ert.amount) from exception_record_t ert where ert.execChargid="+id;
		exceptionRecordModel.setVariable(exceptionRecordModel.getFare()-HibernateUtil.executeSQLQueryInt(varsql));
		
		return exceptionRecordModel;
	}
	
	
	@Override
	public ExceptionRecordModel getCompanyByExchageid(String id) {
		// TODO Auto-generated method stub
		
		
		String sql="SELECT\n" +
				"	ait.available_balance balance,\n" +
				"	aut1. NAME personName,\n" +
				"	aut2.account,\n" +
				"	aut2.NAME accountName,\n" +
				"   aut2.id accountid,\n" +
				"   eert.fare\n" +
				"FROM\n" +
				"	exchange_electric_record_t eert\n" +
				"LEFT JOIN car_account_t cat ON cat.del = 0\n" +
				"AND cat.id = eert.carAccountid\n" +
				"LEFT JOIN account_user_t aut1 ON aut1.id = cat.accountid\n" +
				"AND aut1.del = 0\n" +
				"LEFT JOIN car_t ct on ct.id=cat.carid and ct.del=0 \n" +
				"LEFT JOIN account_user_t aut2 ON aut2.id = ct.companyid  \n" +
				"AND aut2.del = 0\n" +
				"LEFT JOIN account_info_t ait ON ait.accountid = aut2.id\n" +
				"where eert.id='"+id+"'";
	 
		
		ExceptionRecordModel exceptionRecordModel=(ExceptionRecordModel) HibernateUtil.executeSQLQueryObject(sql, ExceptionRecordModel.class);
		
		return exceptionRecordModel;
	}

	@Override
	public AjaxObj insertExceptionRecordModel(
			ExceptionRecordModel exceptionRecordModel) {
		// TODO Auto-generated method stub
		AjaxObj ajaxObj=new AjaxObj();
		ajaxObj.setResult(true);
		ExceptionRecord  exceptionRecord = new ExceptionRecord();

		try {
			PropertyUtils.copyProperties(exceptionRecord,
					exceptionRecordModel);
			exceptionRecord.setDel(0);
			exceptionRecord.setCreatedate(new Date());
			exceptionRecord.setOperid(getLoginUser().getId());
			exceptionRecord.setOperdate(new Date());
			HibernateUtil.save(exceptionRecord);

		} catch (Exception e) {
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("添加时出错");
		}
		return ajaxObj;
		
	}
	
	public void doDownloadAction(HttpServletRequest request,
			HttpServletResponse response,String sql) {
		
		ExcelExportor<String[]> exproter = new ExcelExportor<String[]>();
		try
		{
			String entity = null;
			String task =request.getParameter("task");
			if ("company".equals(task)) {
				entity="公司";
			} else if ("person".equals(task) || StringUtils.isEmpty(task)) {
				entity="个人";
			}
			
			
			response.setHeader("content-disposition", "attachment;filename="
					+ URLEncoder.encode(DateUtils.getDateTime("yyyyMMdd")+entity+"交易异常列表.xls", "UTF-8"));
			OutputStream out = response.getOutputStream();

			List<ExceptionRecordModel> items= HibernateUtil.executeSQLQueryList(sql, ExceptionRecordModel.class);
			
			List<String[]> rows = new ArrayList<String[]>();
						
			String[] header =  new String[] { "日期", "流水号", "账号",
					"所属"+entity, "手机号", "申请异常金额", "异常理由", "状态","操作员"};
			
	

			
			for (ExceptionRecordModel item : items)
			{
				String[] row = new String[header.length];
				row[0] = DateUtils.formatDate(item.getCreatedate(), "yyyy-MM-dd HH:mm:ss") ;
				row[1] =item.getSerialNum();

				row[2] = item.getAccount();
				row[3] = item.getAccountName();
				row[4] = item.getTel();
				row[5] = String.valueOf((item.getAmount()/100));

				row[6] = item.getReason();
				row[7] = item.getStatusName();
				row[8] = item.getOpername();
				rows.add(row);
			}
			exproter.exportExcel(DateUtils.getDateTime("yyyyMMdd")+entity+"交易异常列表", header, rows, out, null);
		}
		catch (Exception e)
		{
			LogUtils.error(e);
		}
	}
	
}